package jlcdata

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"regexp"
	"strconv"
	"strings"

	"github.com/cz-theng/czkit-go/log"
)

const (
	_queryCFormFmt = `catalogNodeId=312&pageNumber=%d&querySortBySign=0&showOutSockProduct=1&showDiscountProduct=1&queryBeginPrice=&queryEndPrice=&queryProductArrange=&queryProductGradePlateId=&queryParameterValue=&queryProductStandard=&queryReferenceEncap=&queryProductLabel=&lastParamName=&baseParameterCondition=&parameterCondition=`
	_queryCURL     = `https://list.szlcsc.com/products/list`
)

var (
	_totalCountregexp = regexp.MustCompile(`totalCount: '(\d+)',`)
)

func queryCapacitanceCount() (uint32, error) {
	resp, err := http.Get("https://list.szlcsc.com/catalog/312.html")
	if err != nil {
		log.Error("Get Capacitance page error:%s", err.Error())
		return 0, err
	}

	buf := new(bytes.Buffer)
	if _, err := buf.ReadFrom(resp.Body); err != nil {
		log.Error("ReadFrom response  error:%s", err.Error())
		return 0, err
	}
	params := _totalCountregexp.FindSubmatch(buf.Bytes())
	if len(params) != 2 { // 1 is the full string
		log.Error("params > 1 they are %v", params)
		return 0, errors.New("Multi Count")
	}
	totalCount, err := strconv.ParseUint(string(params[1]), 10, 32)
	if err != nil {
		log.Error("parse count error:%s", err.Error())
		return 0, err
	}
	return uint32(totalCount), nil
}

func queryCapacitance(page int32) (prodcuts *ProductList, err error) {
	if page < 1 {
		return nil, errors.New("page number > 1")
	}

	cli := &http.Client{}
	formData := fmt.Sprintf(_queryCFormFmt, page)
	req, err := http.NewRequest("POST", _queryCURL, strings.NewReader(formData))
	if err != nil {
		log.Error("new request:%s", err.Error())
		return nil, err
	}
	req.Header.Add("accept", "application/json")
	req.Header.Add("content-type", "application/x-www-form-urlencoded; charset=UTF-8")
	req.Header.Add("x-requested-with", "XMLHttpRequest")
	req.Header.Add("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36")
	// do request
	resp, err := cli.Do(req)
	if err != nil {
		log.Error("do request:%s", err.Error())
		return nil, err
	}
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		err := errors.New(resp.Status)
		log.Error("do request:%s", err.Error())
		return nil, err
	}
	rspDecoder := json.NewDecoder(resp.Body)
	prodcuts = &ProductList{}
	if err = rspDecoder.Decode(prodcuts); err != nil {
		log.Error("request error:%s", err.Error())
		return nil, err
	}
	log.Info("this page has %d", len(prodcuts.ProductRecordList))

	return prodcuts, nil
}
